package com.ajk.server.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.ajk.server.dao.CheckItemDictMapper;
import com.ajk.server.dao.DictDiseaseKeyMapper;
import com.ajk.server.model.CheckItemDict;
import com.ajk.server.model.DictDiseaseKey;
import com.ajk.server.model.Disease;
import com.ajk.server.model.query.CheckItemDictQuery;
import com.ajk.server.service.DictDiseaseKeyService;
import com.ajk.server.service.DiseaseService;
import com.ajk.server.utils.FileStoreUtil;
import com.ajk.server.utils.RedisKeyUtil;

@Service
public class DictDiseaseKeyServiceImpl implements DictDiseaseKeyService{

	@Autowired
	private DiseaseService diseaseService;
	@Autowired
	private DictDiseaseKeyMapper dictDiseaseKeyMapper;
	
	@Autowired
	RedisTemplate<String,Object> template;
	
	@Autowired
	private CheckItemDictMapper checkItemDictMapper;
	
	@Override
	public List<DictDiseaseKey> queryDictDiseaseKey(Integer diseaseId) {
		Disease disease = diseaseService.findDiseaseByIdWithCache(diseaseId);
		
		String key = RedisKeyUtil.dictDiseaseListKey();
		if(!template.hasKey(key)){
			syncInRedis(true);
		}
		List<Object> list = template.opsForList().range(key, 0, -1);
		List<DictDiseaseKey> dictDiseaseKeyList = new ArrayList<DictDiseaseKey>();
		if (CollectionUtils.isNotEmpty(list)) {
			for (Object object : list) {
				if(object instanceof DictDiseaseKey){
					dictDiseaseKeyList.add((DictDiseaseKey) object);
				}
			}
		}
		
		
		CheckItemDictQuery query = new CheckItemDictQuery();
		query.setLimit(0);
		query.setStart(0);
		query.setDiseaseId(diseaseId);
		List<CheckItemDict> dicts =  checkItemDictMapper.findByQuery(query);
		disease.setCheckItemDicts(dicts);
		
		disease.setDictDiseaseKeyList(dictDiseaseKeyList);
		disease.mergeData();
		List<DictDiseaseKey> item = disease.getDictDiseaseKeyList();
		for(int i = item.size()-1;i>=0;i--){
			DictDiseaseKey dictDiseaseKey = item.get(i);
			if(StringUtils.isEmpty(dictDiseaseKey.getContent())){
				item.remove(i);
			}
		}
		return item;
	}
	
	@Override
	public void syncInRedis(boolean force) {
		String key = RedisKeyUtil.dictDiseaseListKey();
		if(force || (!template.hasKey(key) )){
			template.delete(key);
			List<DictDiseaseKey> dictDiseaseKeyList = dictDiseaseKeyMapper.findAll();
			if (CollectionUtils.isNotEmpty(dictDiseaseKeyList)) {
				for (DictDiseaseKey dictDiseaseKey : dictDiseaseKeyList) {
					FileStoreUtil.dealDictDiseaseKeyIcon(dictDiseaseKey);
				}
				template.opsForList().rightPushAll(key, dictDiseaseKeyList.toArray());
			}
		}
	}

}
